<?php

namespace app\admin\controller;

use app\admin\controller\CommonController;
use think\Validate;
use think\Db;
use app\util\Utils;
use app\admin\model\RedPacketRecharge;
use app\admin\model\RedPacketSetup;
use app\admin\model\RedPacketCtm;

class RedpacketController extends CommonController {
    /*
     * 充值记录
     * author xfwed 
     * date 2021.04.14
     */

    public function redPacketRecharge() {
        $type = input('param.type'); //0全部 1充值 2支出（发红包）3红包失效退回
        $start_time = input('param.start_time');
        $end_time = input('param.end_time');

        $perPage = input('param.perPage');
        $page = input('param.page');

        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;

        if ($type) {
            $where['type'] = $type;
        }

        if ($start_time && $end_time) {
            $where['add_time'] = ['between', [$start_time, $end_time]];
        }

        $where = isset($where) ? $where : [];
        $list = RedPacketRecharge::where($where)
                ->field('creat_id,red_id', TRUE)
                ->order('add_time desc')
                ->paginate($perPage);
        $num = RedPacketRecharge::where('type', 1)->count(); //累计充值次数
        $money = RedPacketRecharge::where('type', 1)->sum('money'); //累计充值金额
        $sheng = Db::table('sys_dictionary')
                ->where('type', 'RED_PACKET')
                ->value('view'); //当前剩余金额
        $data['num'] = $num;
        $data['money'] = $money;
        $data['sheng'] = $sheng;
        $data['list'] = $list;
        return $this->ajaxReturn(0, '查询成功', $data);
    }

    /*
     * 充值红包
     * author xfwed 
     * date 2021.04.14
     */

    public function addRedPacket() {
        $rule = [
            'money' => 'require',
            'creat_id' => 'require',
            'name' => 'require',
        ];
        $msg = [
            'money.require' => '金额必须',
            'creat_id.require' => '后台管理员id必须',
            'name.require' => '后台管理员姓名必须',
        ];
        $all = input('param.');
        $validate = new Validate($rule, $msg);

        if (!$validate->check($all)) {
            $error = $validate->getError();
            return $this->ajaxReturn(1, $error, null);
        }

        $reason = input('param.reason'); //原因

        $money = $all['money'];
        $creat_id = $all['creat_id'];
        $name = $all['name'];
        Db::startTrans();
        $data['type'] = 1;
        $data['money'] = $money;
        $data['creat_id'] = $creat_id;
        $data['name'] = $name;
        $data['reason'] = $reason;
        $data['add_time'] = date('Y-m-d H:i:s');
        $add = RedPacketRecharge::insert($data);
        $save = Db::table('sys_dictionary')
                ->where('type', 'RED_PACKET')
                ->setInc('view', $money);

        if ($add && $save) {
            Db::commit();
            return $this->ajaxReturn(0, '充值成功', null);
        } else {
            Db::rollback();
            return $this->ajaxReturn(3, '充值失败', null);
        }
    }

    /*
     * 红包列表
     * author xfwed 
     * date 2021.04.14
     */

    public function redPacketSetupList() {
        $name = input('param.name'); //活动名称
        $status = input('param.status'); //0全部 1进行中2已领完3已停止
        $type = input('param.type'); //0全部 1.下单红包2生日红包3节日红包 4活动红包

        $perPage = input('param.perPage');
        $page = input('param.page');

        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;

        if ($name) {
            $where['name'] = ['like', '%' . $name . '%'];
        }

        if ($status == 1) {
            $where['status'] = 1;
            $where['left_num'] = ['>', 0];
        } elseif ($status == 2) {
            $where['left_num'] = 0;
        } elseif ($status == 3) {
            $where['status'] = 2;
        }

        if ($type) {
            $where['type'] = $type;
        }

        $where = isset($where) ? $where : [];
        $list = RedPacketSetup::where($where)
                ->order('add_time desc')
                ->paginate($perPage);
        foreach ($list as $k => $v) {
            if ($v['status'] == 2) {
                $status = 3; //1进行中2已领完3已停止
            } else {
                if ($v['left_num'] > 0) {
                    $status = 1;
                } else {
                    $status = 2;
                }
            }
            $list[$k]['status'] = $status;
        }
        $sheng = Db::table('sys_dictionary')
                ->where('type', 'RED_PACKET')
                ->value('view'); //当前剩余金额
        $data['sheng'] = $sheng;
        $data['list'] = $list;
        return $this->ajaxReturn(0, '查询成功', $data);
    }

    /*
     * 设置红包
     * author xfwed 
     * date 2021.04.14
     */

    public function setupRedPacket() {
        $rule = [
            'name' => 'require',
            'type' => 'require',
            'all_num' => 'require',
            'money' => 'require',
            'num' => 'require',
            'days' => 'require',
            'image' => 'require',
            'creat_id' => 'require',
            'creat_name' => 'require',
            'max_money' => 'require',
        ];
        $msg = [
            'name.require' => '红包名称必须',
            'type.require' => '红包类型必须',
            'all_num.require' => '红包总个数必须',
            'money.require' => '每个红包金额必须',
            'num.require' => '每个红包领取次数必须',
            'days.require' => '红包有效期必须',
            'image.require' => '分享图必须',
            'creat_id.require' => '后台操作者id必须',
            'creat_name.require' => '后台操作者姓名必须',
            'max_money.require' => '每个红包最大金额必须',
        ];
        $all = input('param.');
        $validate = new Validate($rule, $msg);

        if (!$validate->check($all)) {
            $error = $validate->getError();
            return $this->ajaxReturn(1, $error, null);
        }

        $name = $all['name'];
        $type = $all['type'];
        $all_num = $all['all_num'];
        $money = $all['money'];
        $num = $all['num'];
        $days = $all['days'];
        $image = $all['image'];
        $creat_id = $all['creat_id'];
        $creat_name = $all['creat_name'];
        $max_money = $all['max_money'];

        $sheng = Db::table('sys_dictionary')
                ->where('type', 'RED_PACKET')
                ->value('view'); //当前剩余金额
        $allMoney = $all_num * $max_money;
        if ($allMoney > $sheng) {
            return $this->ajaxReturn(3, '金额超出了可用余额', null);
        }
        if($money > $max_money){
            return $this->ajaxReturn(3, '最大金额因大于最小金额', null);
        }

        Db::startTrans();
        //作废现有红包
        $row = RedPacketSetup::where('type', $type)->where('status', 1)->where('left_num', '>', 0)->find();
        if ($row) {
            $oldallMoney = $row['left_num'] * $row['max_money'];

            $RedPacketdata['status'] = 2;
            $saveRedPacket = RedPacketSetup::where('id', $row['id'])->update($RedPacketdata);
            //将剩余的金额加到总金额上
            $savesys_dictionary = Db::table('sys_dictionary')
                    ->where('type', 'RED_PACKET')
                    ->setInc('view', $oldallMoney);
            //添加红包充值记录
            $reddata['type'] = 4;
            $reddata['money'] = $oldallMoney;
            $reddata['creat_id'] = $creat_id;
            $reddata['name'] = $creat_name;
            $reddata['reason'] = '设置新红包，旧红包失效将剩余金额退回';
            $reddata['red_id'] = $row['id'];
            $reddata['add_time'] = date('Y-m-d H:i:s');
            $saveoldRed = RedPacketRecharge::insert($reddata);
        } else {
            $saveRedPacket = true;
            $savesys_dictionary = true;
            $saveoldRed = true;
        }
        //添加新红包
        $data['name'] = $name;
        $data['type'] = $type;
        $data['all_num'] = $all_num;
        $data['left_num'] = $all_num;
        $data['money'] = $money;
        $data['num'] = $num;
        $data['days'] = $days;
        $data['image'] = $image;
        $data['add_time'] = date('Y-m-d H:i:s');
        $data['max_money'] = $max_money;
        $add = RedPacketSetup::insertGetId($data);
        //总金额减去
        $allMoney = $max_money * $all_num;
        $save = Db::table('sys_dictionary')
                ->where('type', 'RED_PACKET')
                ->setDec('view', $allMoney);
        //添加红包充值记录
        $reddata['type'] = 2;
        $reddata['money'] = $allMoney;
        $reddata['creat_id'] = $creat_id;
        $reddata['name'] = $creat_name;
        $reddata['reason'] = '设置红包';
        $reddata['red_id'] = $add;
        $reddata['add_time'] = date('Y-m-d H:i:s');
        $saveRed = RedPacketRecharge::insert($reddata);

        if ($add && $save && $saveRed && $saveRedPacket && $savesys_dictionary && $saveoldRed) {
            Db::commit();
            return $this->ajaxReturn(0, '设置成功', null);
        } else {
            Db::rollback();
            return $this->ajaxReturn(3, '设置失败', null);
        }
    }

    /*
     * 红包失效
     * author xfwed 
     * date 2021.04.14
     */

    public function delRedPacket() {
        $rule = [
            'id' => 'require',
            'creat_id' => 'require',
            'creat_name' => 'require',
        ];
        $msg = [
            'id.require' => '红包id必须',
            'creat_id.require' => '后台操作者id必须',
            'creat_name.require' => '后台操作者姓名必须',
        ];
        $all = input('param.');
        $validate = new Validate($rule, $msg);

        if (!$validate->check($all)) {
            $error = $validate->getError();
            return $this->ajaxReturn(1, $error, null);
        }

        $id = $all['id'];
        $creat_id = $all['creat_id'];
        $creat_name = $all['creat_name'];

        Db::startTrans();
        $row = RedPacketSetup::where('id', $id)->find();
        if ($row['status'] == 2) {
            return $this->ajaxReturn(3, '该红包已经失效', null);
        }
        if ($row['left_num'] <= 0) {
            return $this->ajaxReturn(3, '该红包已经领完了', null);
        }
        $allMoney = $row['left_num'] * $row['max_money'];

        $data['status'] = 2;
        $saveRedPacket = RedPacketSetup::where('id', $id)->update($data);
        //将剩余的金额加到总金额上
        $save = Db::table('sys_dictionary')
                ->where('type', 'RED_PACKET')
                ->setInc('view', $allMoney);
        //添加红包充值记录
        $reddata['type'] = 3;
        $reddata['money'] = $allMoney;
        $reddata['creat_id'] = $creat_id;
        $reddata['name'] = $creat_name;
        $reddata['reason'] = '红包失效将剩余金额退回';
        $reddata['red_id'] = $id;
        $reddata['add_time'] = date('Y-m-d H:i:s');
        $saveRed = RedPacketRecharge::insert($reddata);
        if ($saveRedPacket && $save && $saveRed) {
            Db::commit();
            return $this->ajaxReturn(0, '失效成功', null);
        } else {
            Db::rollback();
            return $this->ajaxReturn(3, '失效失败', null);
        }
    }

    /*
     * 发放记录
     * author xfwed 
     * date 2021.04.14
     */

    public function redPacketCtmList() {
        $setup_id = input('param.setup_id'); //红包id 从红包列表跳进来必传
        $custom_name = input('param.custom_name'); //用户姓名
        $custom_phone = input('param.custom_phone'); //用户手机号
        $add_start_time = input('param.add_start_time');
        $add_end_time = input('param.add_end_time');
        $status = input('param.status'); //0全部 1进行中 2已领完 3已过期
        $lose_start_time = input('param.lose_start_time');
        $lose_end_time = input('param.lose_end_time');
        $name = input('param.name'); //活动名称
        $type = input('param.type'); //0全部 1下单红包 2生日红包3节日红包 4活动红包

        $perPage = input('param.perPage');
        $page = input('param.page');

        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;

        if ($setup_id) {
            $where['rpc.setup_id'] = $setup_id;
        }

        if ($custom_name) {
            $where['c.custom_name'] = ['like', '%' . $custom_name . '%'];
        }

        if ($custom_phone) {
            $where['c.custom_phone'] = $custom_phone;
        }

        if ($add_start_time && $add_end_time) {
            $where['rpc.add_time'] = ['between', [$add_start_time, $add_end_time]];
        }

        if ($status == 1) {//1进行中 2已领完 3已过期
            $where['rpc.end_time'] = ['>', date('Y-m-d H:i:s', time())];
            //$where['rpc.left_json'] = ['neq', 'not null']; //不为空
            $where['rpc.left_json'] = ['<>', '']; //不为空
        } elseif ($status == 2) {
            $where['rpc.left_json'] = '';
        } elseif ($status == 3) {
            $where['rpc.end_time'] = ['<', date('Y-m-d H:i:s', time())];
            $where['rpc.left_json'] = ['<>', '']; //不为空
        }

        if ($lose_start_time && $lose_end_time) {
            $where['rpc.end_time'] = ['between', [$lose_start_time, $lose_end_time]];
        }

        if ($name) {
            $where['rps.name'] = ['like', '%' . $name . '%'];
        }

        if ($type) {
            $where['rpc.type'] = $type;
        }

        $where = isset($where) ? $where : [];

        $list = RedPacketCtm::alias('rpc')
                ->join('custom c', 'c.id = rpc.ctm_id', 'left')
                ->join('red_packet_setup rps', 'rps.id = rpc.setup_id', 'left')
                ->where($where)
                ->field('rpc.*,c.custom_name,c.custom_phone,rps.name')
                ->order('rpc.add_time desc')
                ->paginate($perPage);
        foreach ($list as $k => $v) {
            $end_time = $v['end_time'];
            $left_json = json_decode($v['left_json'], TRUE);
            if ($left_json) {
                if (strtotime($end_time) > time()) {//1进行中 2已领完 3已过期
                    $status = 1;
                } else {
                    $status = 3;
                }
                $yetMoney = $v['money'] - array_sum($left_json); //已领金额
                $yetNum = $v['num'] - count($left_json); //已领次数
            } else {
                $status = 2;
                $yetMoney = $v['money']; //已领金额
                $yetNum = $v['num']; //已领次数
            }
            $list[$k]['status'] = $status;
            $list[$k]['yetMoney'] = $yetMoney;
            $list[$k]['yetNum'] = $yetNum;
            //已奖励金额 查 ai_redpacket"用户领取红包记录" type=8
            $awardMoney = Db::name('redpacket')->where('type', 8)
                    ->where('packet_ctm_id', $v['id'])
                    ->sum('money');
            $list[$k]['awardMoney'] = $awardMoney; //已奖励金额
        }
        //累计 红包个数和金额
        $redNum = RedPacketCtm::alias('rpc')
                ->join('custom c', 'c.id = rpc.ctm_id', 'left')
                ->join('red_packet_setup rps', 'rps.id = rpc.setup_id', 'left')
                ->where($where)
                ->count();
        $redMoney = RedPacketCtm::alias('rpc')
                ->join('custom c', 'c.id = rpc.ctm_id', 'left')
                ->join('red_packet_setup rps', 'rps.id = rpc.setup_id', 'left')
                ->where($where)
                ->sum('rpc.money');
        $data['redNum'] = $redNum;
        $data['redMoney'] = $redMoney;
        $data['list'] = $list;
        return $this->ajaxReturn(0, '查询成功', $data);
    }

    /*
     * 领取/奖励记录
     * author xfwed 
     * date 2021.04.15
     */

    public function redPacketList() {
        $setup_id = input('param.setup_id'); //红包id 从红包列表跳进来必传
        $custom_name = input('param.custom_name'); //用户姓名
        $custom_phone = input('param.custom_phone'); //用户手机号
        $add_start_time = input('param.add_start_time');
        $add_end_time = input('param.add_end_time');
        $phone = input('param.phone'); //红包所属用户手机号
        $red_type = input('param.red_type'); //0全部 1用户领取（2,7） 2平台奖励（8）
        $name = input('param.name'); //活动名称
        $type = input('param.type'); //0全部 1下单红包 2生日红包3节日红包 4活动红包

        $perPage = input('param.perPage');
        $page = input('param.page');

        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;

        if ($setup_id) {
            $where['rpc.setup_id'] = $setup_id;
        }

        if ($custom_name) {
            $where['c.custom_name'] = ['like', '%' . $custom_name . '%'];
        }

        if ($custom_phone) {
            $where['c.custom_phone'] = $custom_phone;
        }

        if ($add_start_time && $add_end_time) {
            $where['r.add_time'] = ['between', [$add_start_time, $add_end_time]];
        }

        if ($phone) {
            $where['c1.custom_phone'] = $phone;
        }

//        if ($red_type == 1) {//0全部 1用户领取（2,7） 2平台奖励（8）
//            $where1['r.type'] = ['in', '2,7'];
//        } elseif ($red_type == 2) {
//            $where1['r.type'] = 8;
//        }
        
        if($red_type){
            $where1['r.type'] = $red_type;
        }

        if ($name) {
            $where['rpc.red_name'] = ['like', '%' . $name . '%'];
        }

        if ($type) {
            $where['rpc.type'] = $type;
        }

        $where['r.packet_ctm_id'] = ['<>', 0];
        $where['r.status'] = 1;
        $where['r.enjoy_type'] = 1;
        $where1 = isset($where1) ? $where1 : [];

        $list = Db::name('redpacket')->alias('r')
                ->join('red_packet_ctm rpc', 'rpc.id = r.packet_ctm_id', 'left')
                ->join('custom c', 'c.id = r.ctm_id', 'left')
                ->join('custom c1', 'c1.id = rpc.ctm_id', 'left')
                ->join('custom c2', 'c2.id = r.enjoy_id', 'left')
                ->where($where)
                ->where($where1)
                ->field('r.id,r.money,r.type,r.note,r.add_time,rpc.type red_type,rpc.red_name,c.custom_name,c.custom_phone,c1.custom_phone red_phone,c2.custom_phone enjoy_phone')
                ->order('r.add_time desc')
                ->paginate($perPage);
        //已领取金额
        $getMoney = Db::name('redpacket')->alias('r')
                ->join('red_packet_ctm rpc', 'rpc.id = r.packet_ctm_id', 'left')
                ->join('custom c', 'c.id = r.ctm_id', 'left')
                ->join('custom c1', 'c1.id = rpc.ctm_id', 'left')
                ->join('custom c2', 'c2.id = r.enjoy_id', 'left')
                ->where($where)
                ->where('r.type', 'in', '2,7')
                ->sum('r.money');
        //已奖励
        $awardMoney = Db::name('redpacket')->alias('r')
                ->join('red_packet_ctm rpc', 'rpc.id = r.packet_ctm_id', 'left')
                ->join('custom c', 'c.id = r.ctm_id', 'left')
                ->join('custom c1', 'c1.id = rpc.ctm_id', 'left')
                ->join('custom c2', 'c2.id = r.enjoy_id', 'left')
                ->where($where)
                ->where('r.type', 8)
                ->sum('r.money');
        $data['getMoney'] = $getMoney;
        $data['awardMoney'] = $awardMoney;
        $data['list'] = $list;
        return $this->ajaxReturn(0, '查询成功', $data);
    }

    /*
     * 美容金统计
     * author xfwed 
     * date 2021.06.16
     */

    public function ctmRedPacketList() {
        $phone = input('param.phone'); //用户的手机号
        $type = input('param.type'); //0全部 红包来源1红包兑换码2下单返红包3体验特权4邀请特权5520抽奖活动,6续费特权 7分享领红包（被分享者得） 8.好友帮领（分享者得） 9.霸王体验美容金 10.消费反美容金 100.过期 101.购买项目使用红包
        $trans_type = input('param.trans_type'); //0全部1.收入 2.支出
        $start_time = input('param.start_time');
        $end_time = input('param.end_time');
        $store_id = input('param.store_id');//支出门店
        $city = input('param.city');//支出地区

        $perPage = input('param.perPage');
        $page = input('param.page');

        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;
        $offset = ($page - 1) * $perPage;
        
        if($store_id){
            $where2['s.id'] = $store_id;
            $type = 101;
            $trans_type = 2;
        }
        if($city){
            $where2['p.id'] = $city;
            $type = 101;
            $trans_type = 2;
        }

        if ($phone) {
            $where['c.custom_phone'] = $phone;
            $ctm_id = Db::name('custom')->where('custom_phone', $phone)->value('id');
            $where1['ctm_id'] = $ctm_id;
        }
        if ($type) {
            $where['r.type'] = $type;
        }
        if ($trans_type) {
            $where['r.trans_type'] = $trans_type;
        }

        if ($start_time && $end_time) {
            $where['r.add_time'] = ['between', [$start_time, $end_time]];
            $where2['o.pay_time'] = ['between', [$start_time, $end_time]];
        }
        
        $where = isset($where) ? $where : [];
        $where1 = isset($where1) ? $where1 : [];
        $where2 = isset($where2) ? $where2 : [];
        if ((empty($type) || $type == 101) && (empty($trans_type) || $trans_type == 2)) {
            $matSql = Db::name('order')
                    ->alias('o')
                    ->join('custom c', 'c.id = o.ctm_id', 'left')
                    ->join('store s','s.id = o.store_id','left')
                    ->join('prov_city_area p','p.id = s.city','left')
                    ->where($where1)
                    ->where($where2)
                    ->where('o.status', 2)
                    ->where('o.red_money', '>', 0)
                    ->field('o.id,o.red_money money,2 trans_type,101 type,o.pay_time add_time,c.custom_phone,c.custom_name,o.ord_num,s.store_name,p.merger_name')
                    ->buildSql();

            $total = Db::name('redpacket')
                    ->alias('r')
                    ->join('custom c', 'c.id = r.ctm_id', 'left')
                    ->join('order o', 'o.id = r.order_id', 'left')
                    ->where($where)
                    ->field('r.id,r.money,r.trans_type,r.type,r.add_time,c.custom_phone,c.custom_name,o.ord_num,"未知" store_name,"未知" merger_name')
                    ->union($matSql, true)
                    ->order('add_time desc')
                    ->select();
            $list = Db::name('redpacket')
                    ->alias('r')
                    ->join('custom c', 'c.id = r.ctm_id', 'left')
                    ->join('order o', 'o.id = r.order_id', 'left')
                    ->where($where)
                    ->field('r.id,r.money,r.trans_type,r.type,r.add_time,c.custom_phone,c.custom_name,o.ord_num,"未知" store_name,"未知" merger_name')
                    ->union($matSql, true)
                    ->order('add_time desc')
                    ->limit($offset, $perPage)
                    ->select();
            $s['total'] = count($total);
            $s['data'] = $list;
        } else {
            $total = Db::name('redpacket')
                    ->alias('r')
                    ->join('custom c', 'c.id = r.ctm_id', 'left')
                    ->join('order o', 'o.id = r.order_id', 'left')
                    ->where($where)
                    ->field('r.id,r.money,r.trans_type,r.type,r.add_time,c.custom_phone,c.custom_name,o.ord_num,"未知" store_name,"未知" merger_name')
                    ->order('add_time desc')
                    ->select();
            $list = Db::name('redpacket')
                    ->alias('r')
                    ->join('custom c', 'c.id = r.ctm_id', 'left')
                    ->join('order o', 'o.id = r.order_id', 'left')
                    ->where($where)
                    ->field('r.id,r.money,r.trans_type,r.type,r.add_time,c.custom_phone,c.custom_name,o.ord_num,"未知" store_name,"未知" merger_name')
                    ->order('add_time desc')
                    ->limit($offset, $perPage)
                    ->select();
            $s['total'] = count($total);
            $s['data'] = $list;
        }



        //当前美容金：用户可用993.00，用户获得9999.00，用户消费3999.00，已过期3945.00
        if ($phone) {
            $ctmRedMoney = Db::name('custom')->where('custom_phone', $phone)->sum('red_money');
        } else {
            $ctmRedMoney = Db::name('custom')->sum('red_money');
        }
        $ctmGetRedMoney = Db::name('redpacket')->where($where1)->where('trans_type', 1)->sum('money');
        $ctmCostRedMoney = Db::name('order')->where($where1)->where('status', 2)->sum('red_money');
        $ctmEndRedMoney = Db::name('redpacket')->where($where1)->where('type', 100)->sum('money');
        $ctmNum = Db::name('redpacket')->where($where1)->group('ctm_id')->count();
        $data['ctmRedMoney'] = $ctmRedMoney;//用户可用
        $data['ctmGetRedMoney'] = $ctmGetRedMoney;//用户获得
        $data['ctmCostRedMoney'] = $ctmCostRedMoney;//用户消费
        $data['ctmEndRedMoney'] = $ctmEndRedMoney;//已过期
        $data['ctmNum'] = $ctmNum;//总用户数
        $data['list'] = $s;
        return $this->ajaxReturn(0, '查询成功', $data);
    }

}
